import { fileURLToPath, URL } from 'node:url'

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueDevTools from 'vite-plugin-vue-devtools'

// 根据环境变量切换代理目标
const backendTarget = process.env.NODE_ENV === 'development'
  ? 'http://localhost:8080'  // 本地开发环境
  : 'http://gezhi-backend:8080'  // Docker生产环境

// https://vite.dev/config/
export default defineConfig({
  plugins: [
    vue(),
    vueDevTools(),
  ],
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url))
    },
  },
  server: {
    proxy: {
      '/api': {
        target: backendTarget,
        changeOrigin: true,
        rewrite: (path) => {
          console.log('[代理前] 请求路径:', path); // 添加日志调试
          const newPath = path.replace(/^\/api/, '');
          console.log('[代理后] 请求路径:', newPath); // 添加日志调试
          return newPath;
        },
        configure: (proxy, options) => {
          // 添加代理请求日志
          proxy.on('proxyReq', (proxyReq, req, res) => {
            console.log('[代理请求] 目标地址:', proxyReq.protocol + '//' + proxyReq.host + proxyReq.path);
          });
          // 添加响应日志
          proxy.on('proxyRes', (proxyRes, req, res) => {
            console.log('[代理响应] 状态码:', proxyRes.statusCode);
          });
        },
      }
    }
  }
})